package com.iot.ammeter.service.impl.web.permission;

import com.iot.ammeter.constant.Constant;
import com.iot.ammeter.dto.web.role.RoleDTO;
import com.iot.ammeter.service.web.role.RoleService;
import com.iot.ammeter.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @ClassName: PermissionServiceImpl
 * @Author: Basil
 * @Date: 2021/10/23 下午11:11
 * @Version: 1.0
 * @Description: 权限服务类
 **/
@Service("permission")
@Slf4j
public class PermissionServiceImpl {

    private final RoleService roleService;

    public PermissionServiceImpl(RoleService roleService) {
        this.roleService = roleService;
    }

    /**
     * 是否是管理员
     *
     * @return boolean
     */
    public boolean isAdmin() {
        /**
         * 上下文中获取request
         */
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        /**
         * 获取请求头中的token令牌
         */
        String token = request.getHeader("Authorization");
        if (StringUtils.isEmpty(token)) {
            throw new AccessDeniedException("用户未登录");
        }
        log.info("token->{}", token);
        /**
         * 解析token
         */
        Claims claims;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (ExpiredJwtException e) {
            throw e;
        }
        log.info("claims->{}", claims);
        /**
         * 角色id
         */
        String roleId = (String) claims.get("roleId");
        log.info("roleId->{}", roleId);
        /**
         * 查表，roleId对应是不是admin
         */
        RoleDTO role = roleService.getRoleDetailById(roleId);
        if (!Objects.equals(role.getRoleName(), Constant.RoleName.ADMIN)) {
            throw new AccessDeniedException("用户权限不足");
        }
        return true;
    }
}
